package com.gaofei.jpa.service;


import com.alibaba.fastjson.serializer.SerializerFeature;
import com.gaofei.jpa.dao.AdministrativeDivisionRepository;
import com.gaofei.jpa.dto.AdministrativeDivisionDTO;
import com.gaofei.jpa.entity.AdministrativeDivision;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AdministrativeDivisionServiceImpl implements AdministrativeDivisionService {

    @Autowired
    AdministrativeDivisionRepository administrativeDivisionRepository;

    @Override
    public List<AdministrativeDivisionDTO> findByAdministrativeDivision(String code) {
        //1.把所有数据从数据库中查询出来
        List<AdministrativeDivision> allData = administrativeDivisionRepository.findAll();
        //2.得到所有的省  code:后四位为0000
        List<AdministrativeDivision> provs = allData.stream().filter(item -> item.getCode().endsWith("0000")).collect(Collectors.toList());
        //3.根据省的code 获取市的集合 :后两位为00的为市
        for (AdministrativeDivision prov : provs) {
            //获取所有的地级市
            List<AdministrativeDivision> citys = allData.stream().filter(city -> city.getCode().startsWith(prov.getCode().substring(0, 2)) && city.getCode().endsWith("00") && !city.getCode().endsWith("0000")).collect(Collectors.toList());
            //将市封装进省内
            if (citys != null && citys.size() > 0) {
                for (AdministrativeDivision city : citys) {
                    //从所有数据:allData中拿和当前city编码匹配的区县
                    //code 的前四位一样,就代表是该是下的区或者是县
                    List<AdministrativeDivision> areas = allData.stream().filter(area -> city.getCode().substring(0, 4).equals(area.getCode().substring(0, 4)) && !city.getCode().equals(area.getCode())).collect(Collectors.toList());
                    city.setAdministrativeDivisions(areas);
                }
                prov.setAdministrativeDivisions(citys);
            } else {
                //说明是自治市,获取所有区封装
                citys = allData.stream().filter(area -> area.getCode().substring(0, 3).equals(prov.getCode().substring(0, 3)) && !area.getCode().endsWith("0000")).collect(Collectors.toList());
                prov.setAdministrativeDivisions(citys);
            }
        }

        System.out.println(JSON.toJSONString(provs));
        return null;


    }
}
